﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Checkpoint2XNA.Models.Chess
{
    public class Queen : Model3D
    {
        const float RADIUS_MODIFIER = .2f;
        const float HEIGHT_OFFSET_MODIFIER = 1.5f;
        const float LAST_RADIUS_MODIFIER = .3f;
        const int NUM_SPHERES = 2;

        public SolidSphere[] Spheres;

        public Queen(Vector3 p, float size, ChessSide c): base(p, c)
        {
            Spheres = new SolidSphere[NUM_SPHERES];
            var radius = size * RADIUS_MODIFIER;

            for (int i = 0; i < NUM_SPHERES - 1; i++)
            {
                Spheres[i] = new SolidSphere(new Vector3(p.X, p.Y + radius + radius * i * HEIGHT_OFFSET_MODIFIER, p.Z), radius, Color);
            }

            var lastRadius = size * LAST_RADIUS_MODIFIER;
            Spheres[NUM_SPHERES - 1] = new SolidSphere(new Vector3(p.X, p.Y + lastRadius + radius * (NUM_SPHERES - 1) * HEIGHT_OFFSET_MODIFIER, p.Z), lastRadius, Color);
        }

        public override void MoveTo(Vector3 point)
        {
            var lowY = Spheres[0].Position.Y;
            for (int i = 0; i < NUM_SPHERES; i++)
            {
                Spheres[i].MoveTo(new Vector3(point.X, point.Y + Spheres[i].Position.Y - lowY, point.Z));
            }
            CenterBottom = point;
        }

        public override Microsoft.Xna.Framework.Color GetColorAt(Microsoft.Xna.Framework.Vector3 point)
        {
            return Color;
        }

        public override Microsoft.Xna.Framework.Vector3 GetNormal(Microsoft.Xna.Framework.Vector3 point)
        {
            for(int i = 0 ; i < NUM_SPHERES - 1; i++)
            {
                if (Vector3.Distance(point, Spheres[i].Position) <= Spheres[i].Radius + 1E-2)
                    return Spheres[i].GetNormal(point);
            }
            
            return Spheres[NUM_SPHERES - 1].GetNormal(point);
        }

        public override double RayCollide(Microsoft.Xna.Framework.Vector3 origin, Microsoft.Xna.Framework.Vector3 normalVector)
        {
            var t = Double.MaxValue;
            for (int i = 0; i < NUM_SPHERES; i++)
            {
                double temp;
                if ((temp = Spheres[i].RayCollide(origin, normalVector)) > 0 && temp < t)
                    t = temp;
            }

            return t == Double.MaxValue ? -1 : t;
        }
    }
}
